<template>
  <ContentWrap>
    <!--    顶部查询项-->
    <el-form :model="form" inline label-width="auto">
      <el-form-item :label="t('product.cname')">
        <el-select
          v-model="form.product_id"
          :placeholder="t('product.cname')"
          :filterable="true"
          :multiple="true"
          :remote="true"
          :remote-method="getProductOptions"
          :loading="selectLoading"
          style="width: 250px"
        >
          <el-option
            v-for="item in productList"
            :key="item.id"
            :label="item.cname"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('warehouse.name')">
        <el-tree-select
          v-model="form.warehouse_id"
          :data="warehouseList"
          :placeholder="t('warehouse.name')"
          clearable
          check-strictly
          multiple
          style="width: 250px"
        />
      </el-form-item>
      <el-form-item :label="t('inventory.is_futures')">
        <el-select
          :clearable="true"
          v-model="form.is_futures"
          :placeholder="t('inventory.is_futures')"
          style="width: 250px"
        >
          <el-option
            v-for="item in operatorOptions.is_futures"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('purchase.delivery_date')">
        <el-date-picker
          :clearable="true"
          v-model="form.date"
          type="daterange"
          range-separator="-"
          :start-placeholder="t('common.startTimeText')"
          :end-placeholder="t('common.endTimeText')"
          @change="changeTime"
          :editable="false"
          unlink-panels
        />
      </el-form-item>
      <el-form-item>
        <div class="mobile-button-group horizontal">
          <el-button type="primary" icon="Search" @click="search">{{
            t('common.query')
          }}</el-button>
          <el-button icon="Refresh" @click="reset">{{ t('common.reset') }}</el-button>
        </div>
      </el-form-item>
    </el-form>

    <el-table
      :data="dataList"
      border
      :header-cell-style="{ textAlign: 'center' }"
      @sort-change="handleSortChange"
    >
      <el-table-column
        prop="product_name"
        :label="t('product.cname')"
        align="center"
        header-align="center"
        min-width="200"
      >
        <!-- 名称 -->
      </el-table-column>
      <el-table-column
        prop="warehouse_name"
        :label="t('warehouse.name')"
        align="center"
        header-align="center"
        min-width="100"
      />
      <el-table-column
        prop="is_futures"
        :label="t('inventory.is_futures')"
        align="center"
        header-align="center"
        min-width="70"
      >
        <template #default="{ row }">
          {{ useEnumeratePicker(operatorOptions.is_futures, row.is_futures) }}
        </template>
      </el-table-column>

      <el-table-column
        prop="arrival_date"
        :label="t('purchase.delivery_date')"
        align="center"
        header-align="center"
        min-width="100"
      />
      <el-table-column
        align="center"
        header-align="center"
        prop="total_qty"
        :label="t('purchase.total_quantity')"
        sortable="custom"
      >
        <template #default="scope">
          <ElLink @click="openDialog(scope.row, 'total')" type="primary">
            {{ scope.row.total_qty }}
          </ElLink>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        header-align="center"
        prop="available_shipment_qty"
        :label="t('purchase.total_quantity_can_ship')"
        sortable="custom"
      />

      <el-table-column
        align="center"
        header-align="center"
        prop="shipped_qty"
        :label="t('purchase.total_quantity_shipped')"
        sortable="custom"
      >
        <template #default="scope">
          <ElLink
            @click="openDialog(scope.row, 'shipped')"
            type="primary"
            v-if="scope.row.is_futures === 0"
          >
            {{ scope.row.shipped_qty }}
          </ElLink>
          <span v-else>{{ scope.row.shipped_qty }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        header-align="center"
        prop="lock_qty"
        :label="t('purchase.total_quantity_locked')"
        sortable="custom"
      >
        <template #default="scope">
          <ElLink @click="openDialog(scope.row, 'locked')" type="primary">
            {{ scope.row.lock_qty }}
          </ElLink>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        header-align="center"
        prop="actually_available_qty"
        :label="t('purchase.total_quantity_actual_available')"
        sortable="custom"
      />
    </el-table>

    <!--    分页-->
    <Pagination
      :total="total"
      v-model:page="currentPage"
      v-model:limit="pageSize"
      @pagination="initialize"
    />
  </ContentWrap>
  <!--商品信息发货弹框-->
  <DialogShipped ref="DialogShippedRef" :key="dialogKey" :shopInfo="shopInfo" />
  <!--商品信息发货弹框-->
  <DialogLocked
    ref="DialogLockedRef"
    :key="dialogKey"
    :shopInfo="shopInfo"
    :operatorOptions="operatorOptions"
  />
  <!--商品信息总数弹框-->
  <DialogTotal ref="DialogTotalRef" :key="dialogKey" :shopInfo="shopInfo" />
</template>
<script setup lang="ts">
import { useI18n } from '@/hooks/web/useI18n'
import { nextTick } from 'vue'
import dayjs from 'dayjs'
import { ContentWrap } from '@/components/ContentWrap'
import { useEnumeratePicker, calculateColumnWidth } from '@/utils'
import { getListApi as getProductListApi } from '@/api/product'
import { getEnumApi } from '@/api/warehouse/merchandiseOffers'
import { getSecondWarehouseListApi, warehouseCountApi } from '@/api/warehouse/index'
import DialogShipped from './DialogShipped.vue'
import DialogLocked from './DialogLocked.vue'
import DialogTotal from './DialogTotal.vue'

const { push } = useRouter()
const { t } = useI18n()
const form = ref<Record<string, any>>({
  product_id: '',
  warehouse_id: '',
  is_futures: '',
  date: [],
  arrival_date_start: '',
  arrival_date_end: ''
})
const dataList = ref<any[]>([])
const total = ref<number>(0)
const currentPage = ref<number>(1)
const pageSize = ref<number>(20)

// 排序参数管理
const sortParams = ref<any>({})
const classParams = ref<any>({})

const operatorOptions = ref<any>({})
const getSelectList = async () => {
  const resp = await getEnumApi({ field: 'all' })
  operatorOptions.value = resp.data
}
//初始化请求
const initialize = async () => {
  const params = JSON.parse(JSON.stringify(form.value))
  params.pageIndex = currentPage.value
  params.pageSize = pageSize.value
  delete params.date
  // 添加排序参数
  Object.assign(params, sortParams.value)
  const resp = await warehouseCountApi(params)
  dataList.value = resp.data.list
  total.value = resp.data.total
}
const search = () => {
  initialize()
}
//重置查询项
const reset = () => {
  form.value = {
    product_id: '',
    warehouse_id: '',
    is_futures: '',
    date: [],
    arrival_date_start: '',
    arrival_date_end: ''
  }
  currentPage.value = 1
  total.value = 0
  initialize()
}

onMounted(async () => {
  getSelectList()
  initialize()
  getWarehouseList()
})

// 打开弹窗
const shopInfo = ref<Record<string, any>>({})
const dialogKey = ref(0)
const DialogShippedRef = ref<any>(null)
const DialogLockedRef = ref<any>(null)
const DialogTotalRef = ref<any>(null)
const openDialog = (row, type) => {
  console.log(row, type)
  shopInfo.value = row
  dialogKey.value++
  nextTick(() => {
    if (type === 'shipped') {
      DialogShippedRef.value!.dialogVisible = true
      DialogShippedRef.value!.getData()
    } else if (type === 'locked') {
      DialogLockedRef.value!.dialogVisible = true
      DialogLockedRef.value!.getData()
    } else if (type === 'total') {
      DialogTotalRef.value!.dialogVisible = true
      // 传递四个参数：product_id, warehouse_id, is_futures, arrival_date
      const params = {
        product_id: row.product_id,
        warehouse_id: row.warehouse_id,
        is_futures: row.is_futures,
        arrival_date: row.arrival_date
      }
      console.log('Page.vue openDialog 传递的参数:', params)
      console.log('row 数据:', row)
      DialogTotalRef.value!.getData(params)
    }
  })
}

// 搜索下拉
// 产品异步下拉框
const selectLoading = ref<boolean>(false)
const productList = ref<Array<Record<string, any>>>([])
const getProductOptions = async (value) => {
  if (value) {
    selectLoading.value = true
    const productResp = await getProductListApi({ cname: value })
    productList.value = productResp.data.list
    console.log(666, productList.value)
    selectLoading.value = false
  }
}
//格式化时间
const changeTime = (e: Date[]) => {
  if (e && e.length > 0) {
    form.value.arrival_date_start = dayjs(e[0]).format('YYYY-MM-DD 00:00:00')
    form.value.arrival_date_end = dayjs(e[1]).format('YYYY-MM-DD 23:59:59')
  } else {
    form.value.arrival_date_start = null
    form.value.arrival_date_end = null
  }
}
// 获取仓库
const warehouseList = ref<any[]>([])
const getWarehouseList = async () => {
  try {
    const res = await getSecondWarehouseListApi({ disabled: false })
    if (res?.data?.list) {
      // 直接赋值
      warehouseList.value = res.data.list
    } else {
      warehouseList.value = []
    }
  } catch (error) {
    console.error('获取仓库列表失败:', error)
    warehouseList.value = []
  }
}

// 处理排序变化（排他排序：仅保留当前列）
const handleSortChange = (sort: any) => {
  console.log('sort', sort)
  // sort对象结构: { prop: '排序字段', order: '排序方向(ascending/descending/null)' }

  const { column, prop, order } = sort
  if (!prop) return // 无排序字段时不处理

  // 转换排序方向（统一为服务端格式：asc/desc）
  const sortDirection = order === 'ascending' ? 'asc' : order === 'descending' ? 'desc' : null

  // 排他：清空之前所有的排序状态，仅保留当前列
  sortParams.value = {}
  classParams.value = {}

  if (sortDirection) {
    classParams.value[prop] = column.id
    sortParams.value[prop] = sortDirection
  }

  console.log('sortParams', sortParams.value)
  // 关键：更新表格列头的排序状态样式
  updateSortIcons()
  // 重置页码为1，因为排序后数据会变化
  currentPage.value = 1
  // 调用接口获取排序后的数据
  initialize()
}

// 更新排序图标显示状态
const updateSortIcons = () => {
  // 等待 DOM 更新后执行
  nextTick(() => {
    // 清除所有列的排序图标状态
    document.querySelectorAll('.el-table__header .is-sortable').forEach((caret) => {
      caret.classList.remove('ascending', 'descending')
    })

    // 为有排序的列添加对应样式
    Object.entries(sortParams.value).forEach(([field, direction]) => {
      console.log('field', field)
      console.log('direction', direction)
      const th = document.querySelector(`.el-table__header th.${classParams.value[field]}`)
      console.log('th', `.el-table__header th.${classParams.value[field]}`, th)
      if (th) {
        let classActive = direction + 'ending'
        th.classList.add(classActive as string)
      }
    })
  })
}
</script>

<style scoped>
:deep(.el-table--default .el-table__cell) {
  padding: 2px 0 !important;
}

:deep(.el-table--default .cell) {
  padding: 5px 4px;
}

:deep(.el-form-item__label) {
  min-width: 68px;
}
</style>
